package com.bootdo.coach.api;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;

@Aspect
@Component
public class RequestAspect {
    private static final Logger logger = LoggerFactory.getLogger(RequestAspect.class);

	@Pointcut("execution(public * com.bootdo.coach.api.*.*(..))")
	public void log(){}

	@Before("log()")
	public void exBefore(JoinPoint joinPoint){
		ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = sra.getRequest();
		try {
			logger.info("url:"+request.getRequestURL());
			logger.info("method:"+request.getMethod());
			logger.info("class method:"+joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName());
			logger.info("args:");
			if (joinPoint.getArgs() != null) {
				for (Object item : joinPoint.getArgs()) {
					logger.info("----arg:"+JSON.toJSONString(item));
				}
			}
		} catch (Exception e) {
			logger.error("打印日志报错：" + e.getMessage());
		}
	}

	@After("log()")
	public void exAfter(JoinPoint joinPoint){
		logger.info("class method:"+joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName()+"方法执行完毕！");
	}

	@AfterReturning(returning="result",pointcut="log()")
	public void exAfterReturning(Object result){
		logger.info("执行返回值："+JSON.toJSONString(result));
	}
}
